package com.steamedfish.auctionsecurityserveroauth2.config;

import com.steamedfish.auctionsecurityserveroauth2.filter.AuthenticationSuccessHand;
import com.steamedfish.auctionsecurityserveroauth2.filter.TokenVerifyFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private UserDetailsService myUserDetailsService;


    @Autowired
    private PasswordEncoder passwordEncoder;


    @Autowired
    private AuthenticationSuccessHand authenticationSuccessHand;

    @Autowired
    private TokenVerifyFilter tokenVerifyFilter;


    //认证管理器
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/auctionsecurityserveroauth2/userEntiry/**","/auctionsecurityserveroauth2/service/userEntiry/**").permitAll()
                .antMatchers("/**").authenticated()
                .and()
                .formLogin()
                .successHandler(authenticationSuccessHand)
                .and()
                .logout()
                .and()
                .addFilterBefore(tokenVerifyFilter, UsernamePasswordAuthenticationFilter.class)
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailsService)
                .passwordEncoder(passwordEncoder);
    }
}